import React, { Component } from 'react'
import { connect } from "umi"
import { Button, Card, Steps, Spin, Input, Form, Radio, message, Skeleton, Result, Switch, Row, Col } from "antd"
import ComplexForm from "./components/ComplexForm"
import MockBox from "./components/MockBox"
import styles from "./index.less"
import { save } from '../../services/crudService'

class index extends Component {
  constructor(props) {
    super(props)

    this.state = {
      IsSave: false,
    }
    // request('/api/tables', {
    //   method: 'post',
    //   data: {
    //     tableName,
    //   },
    // }).then(tables => {
    //   this.setState({
    //     tables,
    //   })
    // })
    this.props.dispatch({ type: "crud/fetchDB" })
  }
  render() {
    const onFinish = values => {
      const method = [
        { "List": true },
        { "ListByQuery": true },
        { "Add": values.detail.add },
        { "Edit": values.detail.edit },
        { "Del": values.detail.del },
      ].filter(item => item[Object.keys(item)[0]]).map(item => Object.keys(item)[0]);
      const params = {
        tableName: this.props.crud.tableName,
        projectName: values.projectName,
        table: [...values.detail.idRow, ...values.detail.rtable,],
        CName: values.CName,
        isExport: values.detail.export,
        isImport: values.detail.import,
        isMock: values.isMock,
        mockCount: values.mockCount,
        isModuleSql: values.isModuleSql,
        // isWebControl: values.isWebControl,
        method,
        isMock: values.mockData.isMock,
        mockCount: values.mockData.mockCount,
      }
      this.props.dispatch({ type: "crud/setAll", payload: { ...params } })

      this.props.dispatch({ type: "crud/setcurStep", curStep: 2 })
      this.setState({
        IsSave: false,
      })
      const p = {
        ...params,
        table: params.table.map(item => {
          if (item.enum) {
            return {
              ...item,
              enum: item.enum.filter(fitem => !Object.values(fitem).some(sitem => sitem == "")),
            };
          }
          else {

            return {
              ...item,
              enum: [],
            };
          }

        })
      }

      // //模拟提交
      // setTimeout(() => {
      //   console.log(p)
      //   this.setState({
      //     IsSave: true
      //   })
      // }, 2000);
      // return;

      save(p).then(({ success }) => {
        if (!success) {
          message.error("执行时出现错误，请查看日志");
          return;
        }
        this.setState({
          IsSave: true
        })
      })
    };

    const onFinishFailed = errorInfo => {
      // console.log('Failed:', errorInfo);
      message.error(errorInfo.errorFields[0].errors[0]);
    };
    return (
      <div style={{
        width: "100%",
        maxWidth: "1200px",
        margin: "0 auto",
        padding: "15px"
      }}>
        {/* <Card title={"炒鸡牛B的前后端代码生成系统"} > */}
        <Steps current={this.props.crud.curStep} >
          <Steps.Step title="选择一张数据库表" />
          <Steps.Step title="配置表信息" />
          <Steps.Step title={"代码生成"} status={this.state.IsSave ? "finish" : null} />
        </Steps>
        <div style={{ height: 20 }}></div>
        {this.props.crud.curStep != 0 ? null : <Card>
          <div className={"dbRadio"}>
            <Radio.Group value={this.props.crud.tableName} onChange={(e) => {
              this.props.dispatch({ type: "crud/settableName", tableName: e.target.value })
            }}>
              {this.props.crud.db.map((item, index) => <Radio.Button key={index} value={item.name}>{item.name}</Radio.Button>)}
              {/* <Radio.Button value="Hangzhou">Hangzhou</Radio.Button>
                <Radio.Button value="Shanghai">Shanghai</Radio.Button>
                <Radio.Button value="Beijing">Beijing</Radio.Button>
                <Radio.Button value="Chengdu">Chengdu</Radio.Button> */}
            </Radio.Group>
          </div>
          <div style={{ marginTop: "2em", textAlign: "right" }}>
            <Button type="primary" disabled={this.props.crud.tableName === ""}
              onClick={() => {
                this.props.dispatch({ type: "crud/setcurStep", curStep: 1 })
                this.props.dispatch({ type: "crud/settable", table: [] })
                this.props.dispatch({ type: "crud/fetchTables", payload: { tableName: this.props.crud.tableName } })
              }}
            >下一步</Button>
          </div>
        </Card>}
        {this.props.crud.curStep != 1 ? null : <Card>
          <Form
            ref={r => this.myform = r}
            layout="vertical"
            name="basic"
            initialValues={{
              projectName: this.props.crud.projectName,
              CName: this.props.crud.CName,
              isExport: this.props.crud.isExport,
              isImport: this.props.crud.isImport,
              isMock: this.props.crud.isMock,
              mockCount: this.props.crud.mockCount,
              isModuleSql: this.props.crud.isModuleSql,
              isWebControl: this.props.crud.isWebControl,
              mockData: {
                isMock: this.props.crud.isMock,
                mockCount: this.props.crud.mockCount,
              },
            }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            // scrollToFirstError={true}
            size="middle"
          >
            <Form.Item
              label="表名"
            >
              {this.props.crud.tableName}
            </Form.Item>
            <Row gutter={[24, 24]} >
              <Col span={12}>
                <Form.Item
                  label="项目、模型名（英文）"
                  name="projectName"
                  rules={[{ required: true, message: '请填写项目名' }]}

                >
                  <Input allowClear maxLength={30} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="菜单节点名（中文）"
                  name="CName"
                  rules={[{ required: true, message: '请填写项目名' }]}

                >
                  <Input allowClear maxLength={30} />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={[24, 24]}>
              <Col span={12}>

                <Form.Item
                  label="是否给表添加模拟数据"
                  name="mockData"
                  rules={[{ required: true }]}
                >
                  <MockBox />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="是否执行模块数据SQL"
                  name="isModuleSql"
                  rules={[{ required: true }]}
                  valuePropName="checked"
                >
                  <Switch checkedChildren="是" unCheckedChildren="否" />
                </Form.Item>
              </Col>
              {/* <Col span={8}>
                <Form.Item
                  label="是否生成供前台调用的API"
                  name="isWebControl"
                  rules={[{ required: true }]}
                  valuePropName="checked"
                >
                  <Switch checkedChildren="是" unCheckedChildren="否" />
                </Form.Item>
              </Col> */}
            </Row>
            <Form.Item
              name="detail"
              validateTrigger="onSubmit"
              rules={[{
                validator: (rule, value) => {
                  // const CNames = value.rtable.map(item)
                  if (value.rtable.some(item => item.description == null || item.description == "")) {
                    return Promise.reject('请填写完整字段中文名');
                  }
                  if (value.rtable.every(item => item.isTable == false)) {
                    return Promise.reject('至少保留一个列表项');
                  }
                  if (value.rtable.every(item => item.isForm == false)) {
                    return Promise.reject('至少保留一个表单项');
                  }
                  return Promise.resolve();
                }
              }]}

            >
              {
                this.props.crud.table.length == 0 ? <Skeleton /> : <ComplexForm table={this.props.crud.table} method={this.props.crud.method} isExport={this.props.crud.isExport} isImport={this.props.crud.isImport} />
              }
            </Form.Item>
            <Form.Item style={{ textAlign: "right" }}>
              <Button style={{ marginRight: 10 }}
                onClick={() => {
                  this.props.dispatch({ type: "crud/setcurStep", curStep: 0 })
                }}
              >上一步</Button>
              <Button
                disabled={this.props.crud.table.length == 0}
                type="primary"
                onClick={() => {
                  this.myform.submit()
                  // console.log()
                }}
              >下一步</Button>
            </Form.Item>

          </Form>

          {/* <Button
              onClick={() => {
                this.myform.submit()
                // console.log()
              }}
            >提交</Button> */}
        </Card>}
        {this.props.crud.curStep != 2 ? null : <Card>
          {
            this.state.IsSave ?
              <Result
                status="success"
                title="执行成功"
                subTitle="已成功生成前后端代码，请重新编译"
                extra={[
                  <Button key={"yifa"}
                    onClick={() => {
                      window.location.reload()
                    }}
                  >在来一发</Button>,
                  <Button key={"update"}
                    onClick={() => {
                      this.props.dispatch({ type: "crud/setcurStep", curStep: 1 })
                    }}
                  >修改一下</Button>
                ]}
              />
              :
              <div style={{ height: 315, display: "grid", placeItems: "center" }}>
                <Spin size="large" tip="代码生成中..." />
              </div>
          }
        </Card>}
        {/* </Card> */}
      </div>



    )
  }
}
export default connect(({ crud, loading }) => ({ crud, loading }))(index)
